<template>
	<view class="wanlfind-add-container">
		<view class="post-detail">
			<view class="box">
				<view class="box-item">
					<view class="label">标题</view>
					<view class="value"><input v-model="params.title" type="text" placeholder="请输入标题" /></view>
				</view>
			</view>
			<view class="box">
				<template v-if="params.type_id == 26">
					<view class="box-item" v-if="other_content && (other_content.sub_id == 261 || other_content.sub_id == 262)">
						<view class="label">房屋地址</view>
						<view class="value" @tap="chooseLocation">
							<input v-model="params.address" type="text" placeholder="请输入房屋地址" disabled />
							<view class="icon"><uni-icons type="location" size="20" color="#999"></uni-icons></view>
						</view>
					</view>
				</template>
				<template v-if="params.type_id == 30">
					<view class="box-item" v-if="other_content.sub_id == 302">
						<view class="label">所属行业</view>
						<view class="value industry">
							<uni-data-picker
								v-model="selectIndustry"
								:localdata="industryList"
								popup-title="请选择所属行业"
								@change="onIndustryChange"
							></uni-data-picker>
						</view>
					</view>
					<view class="box-item">
						<view class="label">
							薪资范围
							<text style="font-size: 24rpx; color: #999">（元/月--无输入为面议）</text>
						</view>
						<view class="value money">
							<input v-model="params.lowprice" type="text" placeholder="请输入最低薪资" />
							<view>-</view>
							<input v-model="params.highprice" type="text" placeholder="请输入最高薪资" />
						</view>
					</view>
				</template>
				<template v-if="params.type_id == 29">
					<view class="box-item">
						<view class="label">出发地</view>
						<view class="value"><input v-model="other_content.form" type="text" placeholder="请输入出发地" /></view>
					</view>
					<view class="box-item">
						<view class="label">目的地</view>
						<view class="value"><input v-model="other_content.to" type="text" placeholder="请输入目的地" /></view>
					</view>
					<view class="box-item">
						<view class="label">出发日期</view>
						<view class="value"><input v-model="other_content.date" type="text" placeholder="请输入出发日期" /></view>
					</view>
					<view class="box-item" v-if="other_content.sub_id == 291">
						<view class="label">可乘人数</view>
						<view class="value"><input v-model="other_content.person" type="text" placeholder="请输入可乘人数" /></view>
					</view>
					<view class="box-item" v-if="other_content.sub_id == 292">
						<view class="label">载货重量</view>
						<view class="value"><input v-model="other_content.weight" type="text" placeholder="请输入载货重量" /></view>
					</view>
					<view class="box-item" v-if="other_content.sub_id == 293">
						<view class="label">货物重量</view>
						<view class="value"><input v-model="other_content.goods_weight" type="text" placeholder="请输入货物重量" /></view>
					</view>
				</template>
				<view class="box-item">
					<view class="label">{{ other_content.sub_id ? titleText[other_content.sub_id] : title }}</view>
					<view class="value editor"><editor id="editor" @ready="onEditorReady" @input="onEditorInput" placeholder="编辑动态文案~" /></view>
				</view>
				<view class="box-item">
					<view class="grid col-4 grid-square flex-sub">
						<view v-if="params.images.length > 0" v-for="(item, index) in params.images" :key="index">
							<view class="item img-item" @tap="handlePreview(index)">
								<image :src="$wanlshop.oss(item, 100, 100)" mode="widthFix"></image>
							</view>
							<view class="tag" @tap="handleDelImage(index)"><text class="wlIcon-31guanbi text-white"></text></view>
						</view>

						<view v-if="params.images.length < 8" @tap="handleImage()">
							<view class="item img-item">
								<view class="text-lg text-gray add-img"><text class="wlIcon-tianjia" style="font-size: 60rpx"></text></view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="box">
				<view class="box-item">
					<view class="label">联系人</view>
					<view class="value"><input v-model="params.contact_name" type="text" placeholder="请输入联系人" /></view>
				</view>
				<view class="box-item">
					<view class="label">电话</view>
					<view class="value"><input v-model="params.mobile" type="text" placeholder="请输入电话" /></view>
				</view>
			</view>
			<view class="box">
				<view class="box-item">
					<view class="label">信息发布时效</view>
					<view class="value tags">
						<view
							v-for="(item, index) in dateList"
							:key="index"
							class="tag"
							:class="{ active: item.value == params.price_id }"
							@click="handlePrice(item)"
						>
							<view class="tag-title">{{ item.days_text }}/{{ item.days }}天</view>
							<view class="price">
								押金：
								<text class="text-red">{{ item.price }}</text>
								元
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="box">
				<view class="box-item">
					<view class="label">条款</view>
					<view class="value checkbox">
						<checkbox-group @change="handleAgresChange">
							<checkbox value="agree" :checked="agree" color="#1548d7" style="transform: scale(0.7)" />
							<text
								style="
                  margin-left: 20rpx;
                  position: relative;
                  top: 2rpx;
                  text-decoration: underline;
                "
								@click="handleAgresClick"
							>
								我同意条款，保证信息合法合规
							</text>
						</checkbox-group>
					</view>
				</view>
				<uni-popup ref="popup" type="center" border-radius="10px 10px 0 0">
					<view class="agree-content">
						<view class="title">条款</view>
						<view class="close" @click="close"><uni-icons type="closeempty" size="20"></uni-icons></view>
						<view class="content">
							<view class="text">1、不得发布违反国家法律法规的信息，否则后果自负；</view>
							<view class="text">
								2、请保证你所发布信息的真实性，不得发布虚假信息，对此类信息造成的损失本站不负任何责任，您必须对您所发布的信息负责，否则后果自负；
							</view>
							<view class="text">
								3、发布信息时，请填写清楚您的称呼和联系电话或其他联系方式，便于他人与您联系。确保您发布信息的准确性；
							</view>
							<view class="text">
								4、本站对您所发布的信息有任何的处理和处置权，可不经信息发布人同意删除本站认为应该删除的信息。（包括过期信息）
							</view>
							<view class="text">5、发布信息前了解上述事项并同意，否则不予发布信息。</view>
							<view class="know" @click="close">知道了</view>
						</view>
					</view>
				</uni-popup>
			</view>
			<view class="footer">
				<view class="btn" @tap="handleSubmit">
					{{ info.id ? '确认修改' : '立即发布' }}
					<text style="font-size: 22rpx; color: #f43f3b" v-if="currentPrice.days_text">
						（{{ currentPrice.days_text }}/{{ currentPrice.price }}元）
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import industryData from '@/static/json/industry.json';
export default {
	components: {},
	data() {
		return {
			params: {
				title: '',
				content: '',
				images: [],
				type_id: '',
				price_id: '',
				longitude: '',
				latitude: '',
				province: '',
				city: '',
				area: '',
				address: '',
				mobile: '',
				lowprice: 0.0,
				highprice: 0.0,
				contact_name: '',
				other_content: [
					{
						key: 'title',
						text: '',
						desc: '标题',
						value: ''
					},
					{
						key: 'sub_id',
						text: '',
						desc: '子分类',
						value: ''
					},
					{
						key: 'industry',
						text: '',
						desc: '行业',
						value: ''
					},
					{
						key: 'form',
						text: '',
						desc: '出发地',
						value: ''
					},
					{
						key: 'to',
						text: '',
						desc: '目的地',
						value: ''
					},
					{
						key: 'date',
						text: '',
						desc: '出发日期',
						value: ''
					},
					{
						key: 'person',
						text: '',
						desc: '可乘人数',
						value: ''
					},
					{
						key: 'weight',
						text: '',
						desc: '载货重量',
						value: ''
					},
					{
						key: 'goods_weight',
						text: '',
						desc: '货物重量',
						value: ''
					},
					{
						key: 'price_id',
						text: '',
						desc: '价格类型',
						value: ''
					},
				]
			},
			other_content: {
				sub_id: 0,
				form: '',
				to: '',
				date: '',
				person: '',
				weight: '',
				goods_weight: '',
			},
			dateIndex: null,
			dateList: [],
			dateArray: [],
			price: '',
			real_price: '',
			topicIndex: null,
			topicList: [],
			topicArray: [],
			info: {}, //修改时返回的信息
			topicText: '',

			typePlace: 'bottom', //底部弹窗
			agree: true,
			title: '同城信息服务',
			industryList: industryData,
			selectIndustry: 0,
			titleText: {
				261: '出租信息',
				262: '求租信息',
				263: '出售信息',
				264: '求购信息',
				291: '其他要求',
				292: '其他要求',
				293: '其他要求',
				301: '自我评价',
				302: '职位描述'
			}
		};
	},
	computed: {
		currentPrice() {
			return this.dateList.find(item => item.value == this.params.price_id)|| {};
		}
	},
	onLoad(e) {
		//编辑时获取参数
		if (e.detail !== undefined) {
			let res = JSON.parse(uni.getStorageSync('myDetail'));
			this.info = res;
			this.params = this.info;
			//将图片二维转为一维
			this.params.images = this.info.images.map(obj => obj.url);
			if (this.params.other_content) {
				const other_content = JSON.parse(this.params.other_content);
				this.params.other_content = other_content;
				Object.keys(this.other_content).forEach(key => {
					const index = other_content.findIndex(item => item.key === key);
					if (index !== -1) {
						this.other_content[key] = other_content[index]?.value || "";
					}
				});
				const industryItem = other_content.find(item => item.key === 'industry');
				if (industryItem.value && industryItem.value.length > 0) {
					this.selectIndustry = Number(industryItem.value[industryItem.value.length - 1].value);
				}
				const titleItem = other_content.find(item => item.key === 'title');
				if (titleItem) {
					uni.setNavigationBarTitle({
						title: `发布${decodeURIComponent(titleItem.value)}信息`
					});
				}
				const price = other_content.find(item => item.key === 'price_id');
				if (price) {
					this.params.price_id = price.value;
				}
			}
		} else {
			if (e.type) {
				this.params.type_id = e.type;
				this.title = '同城信息服务';
				uni.setNavigationBarTitle({
					title: `发布${decodeURIComponent(e.title)}信息`
				});
				const titleIndex = this.params.other_content.findIndex(item => item.key === 'title');
				if (titleIndex !== -1) {
					this.params.other_content[titleIndex].value = e.title;
				}
				this.other_content.sub_id = e.sub || 0;
				const index = this.params.other_content.findIndex(item => item.key === 'sub_id');
				if (index !== -1) {
					this.params.other_content[index].value = this.other_content.sub_id;
					this.params.other_content[index].text = this.titleText[this.other_content.sub_id];
				}
			}
			//新增 加载位置，后续版本开启加载写入全局
			this.getAddress();
		}
		this.getPrices();
	},

	methods: {
		//选择定位
		chooseLocation() {
			let _this = this;
			uni.chooseLocation({
				latitude: this.params.latitude,
				longitude: this.params.longitude,
				success: function(res) {
					_this.params.address = res.name;
				}
			});
		},
		//选择行业
		onIndustryChange(e) {
			const index = this.params.other_content.findIndex(item => item.key === 'industry');
			if (index !== -1) {
				this.params.other_content[index].value = e.detail.value;
				this.params.other_content[index].text = e.detail.value.map(item => item.text).join('/');
			}
		},
		handleAgresChange(e) {
			this.agree = e.detail.value.length > 0;
		},
		handleAgresClick() {
			this.$refs.popup.open();
		},
		close() {
			this.$refs.popup.close();
		},

		//切换价目
		handlePrice(item) {
			this.params.price_id = item.value;
			const index = this.params.other_content.findIndex(item => item.key === 'price_id');
			if (index !== -1) {
				this.params.other_content[index].value = item.value;
				this.params.other_content[index].text = item.days_text;
			}
		},

		//异步加载价目
		async getPrices() {
			await uni.request({
				url: '/wanlshop/local_life/getPrices',
				type: 'get',
				success: res => {
					this.dateList = res.data;
					//将话题列表转换为一维数组
					this.dateArray = this.dateList.map(obj => obj.text);
					console.log(res);
				}
			});
		},

		//获取手机号码
		getTel(e) {
			this.params.mobile = e.detail.value;
			var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
			if (!reg.test(this.params.mobile)) {
				console.log('格式不正确');
				this.params.mobile = '';
			}
			console.log(this.params.mobile);
		},

		getOtherContent() {
			let error = '';
			Object.keys(this.other_content).forEach(key => {
				const index = this.params.other_content.findIndex(item => item.key === key);
				if (index !== -1) {
					const item = this.params.other_content[index];
					// if (item.required && !item.value) {
					// 	error = item.desc + '不能为空';
					// 	return false;
					// }
					this.params.other_content[index].value = this.other_content[key]|| "";
				}
			});
			if (error) {
				this.$wanlshop.msg(error);
				return false;
			}
			return true;
		},
		// 发布
		handleSubmit() {
			const params = this.params;
			this.getOtherContent();
			if (!params.title || params.title.length > 10) {
				this.$wanlshop.msg('标题不能为空且最大10个字符');
				return;
			}

			if (!params.content) {
				this.$wanlshop.msg('请编辑动态文案~');
				return;
			}
			if (params.images.length === 0) {
				this.$wanlshop.msg('至少添加一张图片');
				return;
			}
			if (params.contact_name === '') {
				this.$wanlshop.msg('请输入联系人~');
				return;
			}
			if (params.mobile === '') {
				this.$wanlshop.msg('请输入有效的手机号码~');
				return;
			}
			if (params.price_id === '') {
				this.$wanlshop.msg('请选择有效时间~');
				return;
			}
			if (!params.address) {
				this.$wanlshop.msg('地址获取失败~');
				return;
			}
			if (!this.agree) {
				this.$wanlshop.msg('请同意协议');
				return;
			}
			//编辑
			if (this.info.id) {
				uni.request({
					url: '/wanlshop/local_life/updateData',
					method: 'POST',
					data: params,
					success: res => {
						console.log(res);
						this.$wanlshop.msg('修改成功');
						setTimeout(() => {
							uni.switchTab({
								url: `/pages/local`
							});
						}, 1000);
					}
				});
			} else {
				//跳转到支付页面
				//把信息存入数据库，之后跳转到支付的页面
				uni.request({
					url: '/wanlshop/local_life/addData1',
					method: 'POST',
					data: params,
					success: res => {
						let local_id = res.data.data; //获取到新增的本地生活的id
						//如果是7表的本地生活， 就显示发布成功，跳回列表， 如果是大于7的，就跳转到支付页面
						if (params.price_id == 1) {
							this.$wanlshop.msg('发布成功');
							setTimeout(() => {
								uni.switchTab({
									url: `/pages/local`
								});
							}, 3000);
						} else {
							uni.redirectTo({
								url: '/pages/local/pay?price_id=' + params.price_id + '&local_id=' + local_id
							});
						}
					}
				});

				//新增
				// uni.request({
				// 	url: '/wanlshop/local_life/addData',
				// 	method: 'POST',
				// 	data: params,
				// 	success: res => {
				// 		console.log(res)
				// 		//这里如果是 余额不足是，充值时把 充值的类型，和数量带上 ,只传price_id就可以了， 以便后面到期退款的时候使用
				// 		if(res.res.msg == '余额不足'){
				// 			let price_id = this.params.price_id;
				// 			//如果余额不足， 弹出选择支付

				// 			uni.showModal({
				// 				title: '提示',
				// 				content: '余额不足，请充值',
				// 				success: res => {
				// 					if (res.confirm) {
				// 						uni.navigateTo({
				// 							url:'/pages/user/money/recharge?price_id='+price_id
				// 						})
				// 					}
				// 				}
				// 			});
				// 		} else{
				// 			this.$wanlshop.msg('发布成功')
				// 			uni.switchTab({
				// 			 	url:`/pages/local`
				// 			})
				// 		}
				// 	}
				// });
			}
		},

		//选择图片
		handleImage() {
			uni.chooseImage({
				crop: {
					quality: 60
				},
				count: 8, // 默认8
				success: res => {
					uni.request({
						url: '/wanlshop/common/uploadData',
						success: updata => {
							for (let i = 0; i < res.tempFilePaths.length; i++) {
								// 读取图片宽高
								uni.getImageInfo({
									src: res.tempFilePaths[i],
									success: image => {
										uni.uploadFile({
											url: updata.data.uploadurl,
											filePath: image.path,
											name: 'file',
											formData: updata.data.storage == 'local' ? null : updata.data.multipart,
											success: data => {
												this.params.images.push(JSON.parse(data.data).data.url);
											},
											fail: error => {
												uni.showToast({
													title: JSON.parse(error.data).msg,
													icon: 'error',
													position: true
												});
											}
										});
									}
								});
							}
						}
					});
				}
			});
		},
		handlePreview(index) {
			let imgArr = [];
			for (let item of this.params.images) {
				imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
			}
			uni.previewImage({
				urls: imgArr,
				current: imgArr[index],
				indicator: 'number'
			});
		},
		handleDelImage(index) {
			this.params.images.splice(index, 1);
		},
		onEditorInput(e) {
			this.params.content = e.detail.html;
		},
		onEditorReady() {
			// #ifdef MP-BAIDU
			this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId');
			// #endif

			// #ifdef APP-PLUS || H5 ||MP-WEIXIN
			if (this.info.id) {
				//编辑页面时
				uni.createSelectorQuery()
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context;
						this.editorCtx.setContents({
							html: this.info.content
						});
					})
					.exec();
			} else {
				//新增页面时
				uni.createSelectorQuery()
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context;
					})
					.exec();
			}

			// #endif
		},
		getAddress() {
			let res = this.$store.state.common.addressData;
			console.log(res);
			if (Object.keys(res).length !== 0) {
				this.params.longitude = res.longitude;
				this.params.latitude = res.latitude;
				this.params.province = res.address.province;
				this.params.city = res.address.city;
				this.params.area = res.address.district;
				this.params.address = res.address.township + (res.address?.neighborhood?.name || '');
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.post-detail {
	padding: 24rpx;
	padding-bottom: calc(122rpx + env(safe-area-inset-bottom));

	.box {
		background-color: #fff;
		border-radius: 12px;
		padding: 20px;
		margin-bottom: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	}
	.box-item {
		&:not(:last-child) {
			margin-bottom: 40rpx;
		}

		.label {
			margin-bottom: 20rpx;
		}
		.value {
			background-color: #f8f8f8;
			padding: 30rpx;
			border-radius: 16rpx;
			font-size: 28rpx;
			position: relative;
			::v-deep .uni-input-input {
				font-size: 28rpx;
			}
			::v-deep .input-placeholder {
				font-size: 28rpx;
			}
			.icon {
				position: absolute;
				right: 16rpx;
				top: 50%;
				transform: translateY(-50%);
			}
		}
		.editor {
			background: #f8f8f8;
			padding: 30rpx;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
		}
		.checkbox {
			background: #fff;
			padding: 0;
		}
		.tags {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 20rpx;
			background: #fff;
			padding: 0;
			.tag {
				width: calc(50% - 10rpx);
				text-align: center;
				background: #f8f8f8;
				padding: 40rpx 0;
				border-radius: 16rpx;
				.tag-title {
					font-size: 28rpx;
					margin-bottom: 20rpx;
				}
				.price {
					color: #999;
					font-size: 24rpx;
				}
				.text-red {
					font-size: 28rpx;
					color: #ff6666;
				}
			}
			.tag.active {
				background: #1548d7;
				color: #fff;
				.price {
					color: #fff;
				}
			}
		}
		.money {
			display: flex;
			align-items: center;
			gap: 20rpx;
		}
		.industry {
			padding: 20rpx 30rpx;
			::v-deep .input-value {
				border: none;
				padding: 0;
				.placeholder {
					font-size: 28rpx;
				}
			}
		}
	}
	.img-item {
		height: 150rpx;
		width: 150rpx;
	}
	.add-img {
		height: 140rpx;
		width: 140rpx;
		border-radius: 16rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 2rpx solid #e8e8e8;
	}
	::v-deep .ql-container {
		min-height: 260rpx;
		height: 260rpx;
		.ql-editor.ql-blank:before {
			font-style: normal;
			font-size: 28rpx;
		}
	}
	::v-deep .uni-checkbox-input {
		width: 36rpx;
		height: 36rpx;
	}
	.agree-content {
		background-color: #fff;
		width: 80%;
		border-radius: 16rpx;
		overflow: hidden;
		margin: 0 auto;
		position: relative;
		.title {
			background: #eaf2ff;
			font-size: 32rpx;
			text-align: center;
			color: #0c4cff;
			line-height: 96rpx;
		}
		.close {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			font-size: 32rpx;
			color: #0c4cff;
		}
		.content {
			padding: 40rpx 32rpx;
			font-size: 28rpx;
			line-height: 44rpx;
			color: #666;
			.text {
				margin-bottom: 20rpx;
			}
			.know {
				text-align: center;
				font-size: 28rpx;
				background: #0c4cff;
				color: #fff;
				padding: 20rpx 0;
				border-radius: 40rpx;
				width: 60%;
				margin: 60rpx auto 0;
			}
		}
	}
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
		background-color: #fff;
		padding: 24rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
		padding: 30rpx;
		padding-bottom: env(safe-area-inset-bottom);
		.btn {
			width: 100%;
			height: 86rpx;
			line-height: 86rpx;
			text-align: center;
			border-radius: 43rpx;
			font-size: 28rpx;
			color: #fff;
			background-color: #1548d7;
		}
	}
}
</style>
